<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('form', '', 0);
class vote extends admin {
	private $db2,$order,$order_detail, $db;
	function __construct() {
		parent::__construct();
		$this->M = new_html_special_chars(getcache('vote', 'commons'));
		$this->db = pc_base::load_model('vote_subject_model');
		$this->db2 = pc_base::load_model('vote_option_model');
		$this->order = pc_base::load_model('order_model');
		$this->reg_child = pc_base::load_model('reg_child_model');
		$this->order_detail = pc_base::load_model('order_detail_model');
		$model_setting=pc_base::load_model('site_setting_model');
        $this->t_type = $model_setting->getValue("talent_type",$this->get_siteid());//获取人才类型
	}

	public function init() {
		$show_pc_hash = '';

		//获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
        $sdb = pc_base::load_model('vote_data_model'); //加载投票统计的数据模型

		$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
		$infos = $this->db->listinfo(array('siteid'=>$this->get_siteid(),'status'=>1),'id DESC',$page, '14');
		foreach ($infos as $k => $v) {
			$infos[$k]['votenumber'] = $sdb->count(" subjectid = " . $v['id']);
		}
		$pages = $this->db->pages;
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=vote&c=vote&a=add\', title:\''.L('vote_add').'\', width:\'700\', height:\'450\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('vote_add'));
		include $this->admin_tpl('vote_list'); 
 	}

	/*
	 *判断标题重复和验证 
	 */
	public function public_name() {
		$subject_title = isset($_GET['subject_title']) && trim($_GET['subject_title']) ? (pc_base::load_config('system', 'charset') == 'gbk' ? iconv('utf-8', 'gbk', trim($_GET['subject_title'])) : trim($_GET['subject_title'])) : exit('0');
		$subjectid = isset($_GET['subjectid']) && intval($_GET['subjectid']) ? intval($_GET['subjectid']) : '';
		$data = array();
		if ($subjectid) {
			$data = $this->db->get_one(array('id'=>$subjectid), 'subject');
			if (!empty($data) && $data['subject'] == $subject_title) {
				exit('1');
			}
		}
		if ($this->db->get_one(array('subject'=>$subject_title,'status'=>1), 'id')) {
			exit('0');
		} else {
			exit('1');
		}
	}
	
	/*
	 *判断结束时间是否比当前时间小  
	 */
	public function checkdate() {
		$nowdate = date('Y-m-d',SYS_TIME);
		$todate = $_GET['todate'];
		if($todate > $nowdate){
			exit('1');
		}else {
			exit('0');
		}
	}
	
	/**
	 * 添加投票
	 */
	public function add() {
		//读取配置文件
		$data = array();
		$data = $this->M;
		$siteid = $this->get_siteid();//当前站点
		if(isset($_POST['dosubmit'])) {
			$_POST['subject']['addtime'] = date('Y-m-d H:i:s');
			$_POST['subject']['updatetime'] = date('Y-m-d H:i:s');
			$_POST['subject']['created_by'] = $_SESSION['userid'];
			$_POST['subject']['updated_by'] = $_SESSION['userid'];
			$_POST['subject']['siteid'] = $this->get_siteid();
			if(empty($_POST['subject']['subject'])) {
				showmessage(L('vote_title_noempty'),'?m=vote&c=vote&a=add');
			}
 			//记录选项条数 optionnumber 
			//$_POST['subject']['optionnumber'] = count($_POST['option']);
			$_POST['subject']['template'] = $_POST['vote_subject']['vote_tp_template'];
			
 			$post_data = trim_script($_POST);
			$subjectid = $this->db->insert($post_data['subject'],true);

			//记录行为日志
            $log_content = '<span style="color:green;">添加投票</span>[新生成投票id：'.$subjectid.'；标题：'.$post_data['subject']['subject'].']';
            $this->manage_admin_log($log_content);

			if(!$subjectid) return FALSE; //返回投票ID值, 以备下面添加对应选项用,不存在返回错误
			//添加选项操作
			//$this->db2->add_options($post_data['option'],$subjectid,$this->get_siteid());
			//生成JS文件
			//$this->update_votejs($subjectid);
			if(isset($_POST['from_api'])&& $_POST['from_api']) {
				showmessage(L('operation_success'),'?m=vote&c=vote&a=add','100', '',"window.top.$('#voteid').val('".$subjectid."');window.top.art.dialog({id:'addvote'}).close();");
			} else {
				showmessage(L('operation_success'),'?m=vote&c=vote','','add');
 			}
		} else {
			$show_validator = $show_scroll = $show_header = true;
			pc_base::load_sys_class('form', '', 0);
			@extract($data[$siteid]);
			$contest_model = pc_base::load_model('contest_model');
			$vote_group_model = pc_base::load_model('vote_group_model');
			//投票关联少儿报名主题表，查询id和title（nsrweb_reg_child_model）
			$reg_info = $this->reg_child->select('','id,title');
			$reg_infos = array();
			if($reg_info){
			    foreach ($reg_info as $key_1=>$value_1){
			        $reg_infos[$value_1['id']] = $value_1['title'];
			    }
			}
			//获取赛事活动列表
			$select_categorys = $contest_model->now_contest_select();
			$model_setting=pc_base::load_model('site_setting_model');
			//获取一级分组
			$voteGroup = $vote_group_model->getSourceType();
			//获取赛区
        	$contest_district = $model_setting->getValue("contest_district",$this->get_siteid());
			//模版
			pc_base::load_app_func('global', 'admin');
			$siteid = $this->get_siteid();
			$template_list = template_list($siteid, 0);
			$site = pc_base::load_app_class('sites','admin');
			$info = $site->get_by_id($siteid);
			foreach ($template_list as $k=>$v) {
				$template_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($template_list[$k]);
			}
			include $this->admin_tpl('vote_add');
		}

	}

	/**
	 * 编辑投票
	 */
	public function edit() {

		if(isset($_POST['dosubmit'])){
			//验证数据正确性
			$subjectid = intval($_GET['subjectid']);
			if($subjectid < 1) return false;
			if(!is_array($_POST['subject']) || empty($_POST['subject'])) return false;
			if((!$_POST['subject']['subject']) || empty($_POST['subject']['subject'])) return false;
			$_POST['subject']['updatetime'] = date('Y-m-d H:i:s');
			$_POST['subject']['updated_by'] = $_SESSION['userid'];
			$post_data = trim_script($_POST);
			// 	$this->db2->update_options($post_data['option']);//先更新已有 投票选项,再添加新增加投票选项
			// if(is_array($_POST['newoption'])&&!empty($_POST['newoption'])){
			// 	$siteid = $this->get_siteid();//新加选项站点ID
			// 	$this->db2->add_options($post_data['newoption'],$subjectid,$siteid);
			// }
			//模版 
			$_POST['subject']['template'] = $_POST['vote_subject']['vote_tp_template'];
			
			//$_POST['subject']['optionnumber'] = count($_POST['option'])+count($_POST['newoption']);
 			$this->db->update($post_data['subject'],array('id'=>$subjectid));//更新投票选项总数
			//$this->update_votejs($subjectid);//生成JS文件
			//记录行为日志
            $log_content = '<span style="color:blue;">修改投票</span>[投票id：'.$subjectid.'；标题：'.$post_data['subject']['subject'].']';
            $this->manage_admin_log($log_content);

			showmessage(L('operation_success'),'?m=vote&c=vote&a=edit','', 'edit');
		}else{
			$show_validator = $show_scroll = $show_header = true;
			pc_base::load_sys_class('form', '', 0);
			//投票关联少儿报名主题表，查询id和title（nsrweb_reg_child_model）
			$reg_info = $this->reg_child->select('','id,title');
			$reg_infos = array();
			if($reg_info){
			    foreach ($reg_info as $key_1=>$value_1){
			        $reg_infos[$value_1['id']] = $value_1['title'];
			    }
			}
			//解出投票内容
			$info = $this->db->get_one(array('id'=>$_GET['subjectid']));
			if(!$info) showmessage(L('operation_success'));
			extract($info);

			$contest_model = pc_base::load_model('contest_model');
			$vote_group_model = pc_base::load_model('vote_group_model');
			//获取一级分组
			$voteGroup = $vote_group_model->getSourceType();
			//获取赛事活动列表
			$select_categorys = $contest_model->now_contest_select($contest_id);
			$model_setting=pc_base::load_model('site_setting_model');
			//获取赛区
        	$contest_districts = $model_setting->getValue("contest_district",$this->get_siteid());
				
			//解出投票选项
			$this->db2 = pc_base::load_model('vote_option_model');
			$options = $this->db2->get_options($_GET['subjectid']);
			
			//模版
			pc_base::load_app_func('global', 'admin');
			$siteid = $this->get_siteid();
			$template_list = template_list($siteid, 0);
			$site = pc_base::load_app_class('sites','admin');
			$info = $site->get_by_id($siteid);
			foreach ($template_list as $k=>$v) {
				$template_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($template_list[$k]);
			}

			include $this->admin_tpl('vote_edit');
		}

	}

	/**
	 * 投票选项
	 */
	public function options () {
		$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
		$subjectid = (int) $_GET['subjectid'];
		$where = " siteid = ".$this->get_siteid()." and subjectid = " . $subjectid;
		if(isset($_GET['name']) && !empty($_GET['name'])) {
			$name = trim($_GET['name']);
			$where .= " and `option` like '%$name%' ";
		}
		$info = $this->db->get_one(array('id'=>$subjectid));
		$optionsList = $this->db2->listinfo($where,'listorder DESC,id DESC',$page, '10');
		$pages = $this->db2->pages;
		//var_dump($optionsList);die;
		include $this->admin_tpl('vote_options');
	}

	/**
	 * 投票选项排序
	 */
	public function listorder (){
		if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {
                $res = $this->db2->update(array('listorder'=>$listorder), array('id'=>$id));
            }
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
	}

	/**
     * 投票选项删除、批量删除
     */
    public function vote_del()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $option_name = array();
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                    $info = $this->db2->get_one(array('id'=>$v));
        			$option_name[] = $info['option'];
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        } else {
        	$info = $this->db2->get_one(array('id'=>$id));
        	$option_name[] = $info['option'];
        }
        $result = $this->db2->delete("id in ('$id')");

        //记录行为日志
        $id = safe_replace($id);
    	$option_name = implode(',',$option_name);
        $log_content = '<span style="color:red;">批量删除选项</span>[选项id：('.$id.'),选项:('.$option_name.')]';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 投票选项添加
     */
    public function bindTalent(){
        $types = $this->t_type;//var_dump($types);die;
        $subjectid= (int) $_REQUEST['subjectid'];
        $subject_type = (int) $_REQUEST['subject_type'];
        $talent_array = $this->db2->select(array("subjectid"=>$subjectid),"source_id");
        $where = " status = 1 AND siteid = " . $this->get_siteid();
        $ids = array();
        if(!empty($talent_array)){
            foreach ($talent_array as $k => $v) {
                $ids[] = intval($v['source_id']);
            }
            $ids = implode('\',\'', $ids);
            $where.=" and id not in ('$ids')";
        }
        if ($subject_type == 1) { //人才
        	if (isset($_GET['real_name']) && !empty($_GET['real_name'])) {
	            $name = trim($_GET['real_name']);
	            $where .= " and `real_name` like '%$name%' ";
	        }
	        if (isset($_GET['talent_type']) && !empty($_GET['talent_type'])) {
	            switch ($_GET['talent_type']) {
	                case '1':
	                    $where .= " and is_student = 1";
	                    break;
	                case '2':
	                    $where .= " and is_signed_model = 1";
	                    break;
	                case '3':
	                    $where .= " and is_hot = 1";
	                    break;
	                case '4':
	                    $where .= " and is_judge = 1";
	                    break;
	                case '5':
	                    $where .= " and is_guest = 1";
	                    break;
	                case '6':
	                    $where .= " and is_star = 1";
	                    break;
	                case '7':
	                    $where .= " and is_mentor = 1";
	                    break;
	                case '8':
	                    $where .= " and is_moter = 1";
	                    break;
	                default:
	                    break;
	            }
	        }
	        $talent_model = pc_base::load_model('talent_model');
	        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
	        $url = "?m=vote&c=vote&a=bindTypetalent&subjectid=".$subjectid;
	        $infos=$talent_model->listinfo($where,'id DESC',$page,10);
	        $pages = $talent_model->pages;
	        include $this->admin_tpl('bindTalent');
        } else if ($subject_type == 2 || $subject_type == 3) { //赛事和活动
        	$tree = pc_base::load_sys_class('tree');
	        $sitelist = getcache('sitelist','commons');
	        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
	        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	        $categorys = array();
	        $id1 = array();
	        if(!empty($talent_array)){
	            foreach ($talent_array as $k => $v) {
	                $id1[] = intval($v['source_id']);
	            }
	        }
	        $where = " status = 1 AND siteid = " . $this->get_siteid() ." AND end_time > '" . date('Y-m-d H:i:s') ."' ";
	        if ($subject_type == 2) {
	        	$where .= " AND is_activity = 0 ";
	        } else {
	        	$where .= " AND is_activity = 1 ";
	        }
	        $contest_model = pc_base::load_model('contest_model');
	        $infos = $contest_model->select($where, '*', '', 'id DESC');
	        foreach ($infos as $k => $v) {
	            if(in_array($v['id'],$id1)) {
	                $v['statusid'] = 1;
	                $v['statusname'] = '<span style="color:red;">已添加选项</span>';
	            } else {
	                $v['statusid'] = 0;
	                $v['statusname'] = '<span style="color:green;">未添加选项</span>';
	            }
	            $categorys[$v['id']] = $v;
	        }
	        $str  = "<tr onclick='select_list(this,\$id)' class='cu' data='\$statusid' title='click_to_select'>
	                    <td align='left'>\$spacer\$name\$display_icon</td>
	                    <td >\$year</td>
	                    <td>\$begin_time</td>
	                    <td>\$end_time</td>
	                    <td>\$statusname</td>
	                </tr>";
	        $tree->init($categorys);
	        $categorys = $tree->get_tree(0, $str);
	        include $this->admin_tpl('bindContest');
        } else if ($subject_type == 4) { //机构
        	if (isset($_GET['name']) && !empty($_GET['name'])) {
	            $name = trim($_GET['name']);
	            $where .= " and `name` like '%$name%' ";
	        }
	        $agency_nsr_model = pc_base::load_model('agency_nsr_model');
	        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

	        $infos=$agency_nsr_model->listinfo($where,'id DESC',$page,10);
	        $pages = $agency_nsr_model->pages;
	        include $this->admin_tpl('bindAgency');
        } else if ($subject_type == 5) { //课程
        	if (isset($_GET['name']) && !empty($_GET['name'])) {
	            $name = trim($_GET['name']);
	            $where .= " and `name` like '%$name%' ";
	        }
	        $course_nsr_model = pc_base::load_model('course_nsr_model');
	        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

	        $infos=$course_nsr_model->listinfo($where,'id DESC',$page,10);
	        $pages = $course_nsr_model->pages;
	        include $this->admin_tpl('bindCourse');
        } else if ($subject_type == 6) { //通用
        	include $this->admin_tpl('addoptions');
        }
    }

    /**
     * 投票选项添加完成
     */
    public function bindOptionAjax (){
    	$model_setting=pc_base::load_model('site_setting_model');
        //获取人才类型对应投票数初始值
        $talent_num = $model_setting->getValue("talent_origin_num",$this->get_siteid());

    	$subjectid= (int) $_REQUEST['subjectid'];
        $subject_type = (int) $_REQUEST['subject_type'];
        $relation=$_REQUEST['relation'];
        $contest=explode("|",$relation);
        $data=array();
        if ($subject_type == 6) {
        	$option = explode(",",$relation);
        	$data['siteid'] = $this->get_siteid();
        	$data['subjectid'] = $subjectid;
        	$data['option'] = $option[0];
        	$data['image'] = $option[1];
        	$res = $this->db2->insert($data,true);
        	if($res){

        		//记录行为日志
                $log_content = '<span style="color:green;">添加选项</span>[新生成选项id：'.$res.'，选项：'.$data['option'].']';
                $this->manage_admin_log($log_content);

	            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"添加选项成功"));die;
	        }else{
	            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"添加选项失败"));die;
	        }
        }
        $talent_name = array();
        foreach($contest as $k=>$v){
            $data[$k]['siteid']=$this->get_siteid();
            $data[$k]['subjectid']=$subjectid;
            $data[$k]['source_id']=$v;
            if ($subject_type == 1) {
	        	$models = pc_base::load_model('talent_model');
	        } else if ($subject_type == 2 || $subject_type == 3){
	        	$models = pc_base::load_model('contest_model');
	        } else if ($subject_type == 4) {
	        	$models = pc_base::load_model('agency_nsr_model');
	        } else if ($subject_type == 5) {
	        	$models = pc_base::load_model('course_nsr_model');
	        }
	        $info = $models->get_one(array('id'=>$v));
	        if ($info['is_student'] == 1) {
	        	$type_id = 1;
	        } else if($info['is_signed_model'] == 1) {
	        	$type_id = 2;
	        } else if($info['is_hot'] == 1) {
	        	$type_id = 3;
	        } else if($info['is_judge'] == 1) {
	        	$type_id = 4;
	        } else if($info['is_guest'] == 1) {
	        	$type_id = 5;
	        } else if($info['is_star'] == 1) {
	        	$type_id = 6;
	        } else if($info['is_mentor'] == 1) {
				$type_id = 7;	        	
	        } else if($info['is_moter'] == 1) {
	        	$type_id = 8;
	        }
        	$data[$k]['option'] = $subject_type == 1?$info['real_name']:$info['name'];
        	$data[$k]['image'] = $info['image_square'];
        	$data[$k]['origin_num'] = $talent_num[$type_id]['origin_num'];
        	$talent_name[] = $subject_type == 1?$info['real_name']:$info['name'];  
        }
        $res = $this->db2->multiInsert($data);
        if($res){

        	//记录行为日志
        	$talent_id = implode(',',$contest);
        	$talent_name = implode(',',$talent_name);
            $log_content = '<span style="color:green;">批量添加选项</span>[人才id：('.$talent_id.'),选项:('.$talent_name.')]';
            $this->manage_admin_log($log_content);

            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"投票选项添加成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"投票选项添加失败"));
        }
    }

    /**
     * 投票选项图片修改
     */
    public function editoption ()
    {
    	if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && !empty($_POST['dosubmit'])) {
        	$post = $_POST;
        	$data = array();
        	$data['image'] = $post['images'];
        	$data['origin_num'] = $post['origin_num'];
            $ids = $this->db2->update($data, array('id'=>$id));
            if ($ids) {

            	//记录行为日志
                $log_content = '<span style="color:blue;">修改选项图片</span>[选项id：'.$id.']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), HTTP_REFERER,"","edit");
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }   
        } else {
            $info = $this->db2->get_one(array('id'=>$id));
            extract($info);
            //获取站点模板信息
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('editoptions');
        }
    }

    /**
     * 投票选项金额修改
     */
    public function editoptionmoney ()
    {
    	if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && !empty($_POST['dosubmit'])) {
        	$money_money = pc_base::load_model('vote_option_money_detail_model');
        	$info = $this->db2->get_one(array('id'=>$id));
        	$post = $_POST;
        	$data = array();
        	$datas = array();
        	$datas['add_or_sub'] = $post['add_or_sub'];
        	$datas['money'] = $post['money'];
        	$datas['desc'] = $post['desc'];
        	$datas['create_time'] = date('Y-m-d H:i:s');
        	$datas['source_type'] = 2;
        	$datas['source_id'] = 0;
        	$datas['option_id'] = $id;
        	$money_money->insert($datas,true);
        	if ($post['add_or_sub'] == 1) {
        		$data['money'] = $info['money'] + $post['money'];
        	} else {
        		$data['money'] = $info['money'] - $post['money'];
        	}
            $ids = $this->db2->update($data, array('id'=>$id));
            if ($ids) {

            	//记录行为日志
                $log_content = '<span style="color:blue;">修改选项金额</span>[选项id：'.$id.']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), HTTP_REFERER,"","edit");
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }   
        } else {
            //获取站点模板信息
            $show_validator = true;
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('editoptionmoney');
        }
    }

    /**
     * 投票选项金额明细
     */
    public function optionmoneylist ()
    {
    	$money_money = pc_base::load_model('vote_option_money_detail_model');
    	if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $page = $_GET['page']?(int)$_GET['page']:1;
        $id = $_REQUEST['id'];
        $info = $this->db2->get_one(array('id'=>$id));
        $where = ' option_id = '.$id;
        if (isset($_GET['add_or_sub']) && $_GET['add_or_sub']) {
        	$add_or_sub = trim($_GET['add_or_sub']);
        	$where .= " and add_or_sub = ".$add_or_sub;
        }
        if (isset($_GET['source_type']) && $_GET['source_type']) {
        	$source_type = trim($_GET['source_type']);
        	$where .= " and source_type = ".$source_type;
        }
        $lists = $money_money->listinfo($where,'create_time DESC',$page, '20');
		$pages = $money_money->pages;
    	include $this->admin_tpl('optionmoneylist');
    }

    /**
     * 选项图片一键替换
     */
    public function editImageOption ()
    {
    	$subjectid= (int) $_REQUEST['subjectid'];
    	$source_array=$this->db2->select(array("subjectid"=>$subjectid),"source_id,id");
    	foreach ($source_array as $v) {
    		$model = pc_base::load_model('talent_model');
    		$talentInfo = $model->get_one(array('id'=>$v['source_id']),'image_square');
    		$data = array();
    		$data['image'] = $talentInfo['image_square'];
    		$this->db2->update($data,array('id'=>$v['id']));
    	}
    	echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键替换成功"));die;
    }

    /**
     * ajax一键导入类型下人才
     */
    public function bindTypetalent ()
    {
        $model_setting=pc_base::load_model('site_setting_model');
        //获取人才类型对应投票数初始值
        $talent_num = $model_setting->getValue("talent_origin_num",$this->get_siteid());

        $subjectid= (int) $_REQUEST['subjectid'];
        $type_id = (int) $_REQUEST['type_id'];
        $source_array=$this->db2->select(array("subjectid"=>$subjectid),"source_id");
        //组合条件
        $where = " status = 1 ";
        if (isset($type_id) && !empty($type_id)) {
            switch ($type_id) {
                case '1':
                    $where .= " and is_student = 1";
                    break;
                case '2':
                    $where .= " and is_signed_model = 1";
                    break;
                case '3':
                    $where .= " and is_hot = 1";
                    break;
                case '4':
                    $where .= " and is_judge = 1";
                    break;
                case '5':
                    $where .= " and is_guest = 1";
                    break;
                case '6':
                    $where .= " and is_star = 1";
                    break;
                case '7':
                    $where .= " and is_mentor = 1";
                    break;
                case '8':
                    $where .= " and is_moter = 1";
                    break;
                default:
                    break;
            }
        }
        if(!empty($source_array)){
            foreach ($source_array as $k => $v) {
                $id[] = intval($v['source_id']);
            }
            $id = implode('\',\'', $id);
            $where.=" and id not in ('$id')";
        }
        $model = pc_base::load_model('talent_model');
        $info = $model->select($where,'id,real_name,image_square');
        $data=array();
        $talent_id = array();
        $talent_name = array();
        foreach($info as $k=>$v){
        	$talent_id[] = $v['id'];
        	$talent_name[] = $v['real_name'];
            $data[$k]['siteid']=$this->get_siteid();
            $data[$k]['source_id']=$v['id'];
            $data[$k]['subjectid']=$subjectid;
            $data[$k]['option'] =  $v['real_name'];
            $data[$k]['image'] =  $v['image_square'];
            $data[$k]['origin_num'] =  $talent_num[$type_id]['origin_num'];
        }
        if (empty($data)) {
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功"));die;
        }
        $res=$this->db2->multiInsert($data);

        //记录行为日志
    	$talent_id = implode(',',$talent_id);
    	$talent_name = implode(',',$talent_name);
        $log_content = '<span style="color:green;">批量导入人才选项</span>[人才id：('.$talent_id.'),选项:('.$talent_name.')]';
        $this->manage_admin_log($log_content);

        if($res){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"一键导入失败"));
        }
    }

	/**
	 * 删除投票 
	 * @param	intval	$sid	投票的ID，递归删除
	 */
	public function delete() {
		if((!isset($_GET['subjectid']) || empty($_GET['subjectid'])) && (!isset($_POST['subjectid']) || empty($_POST['subjectid']))) {
			showmessage(L('illegal_parameters'), HTTP_REFERER);
		} else {
				
			if(is_array($_POST['subjectid'])){
				$subjectid = implode(',',$_POST['subjectid']);
				foreach($_POST['subjectid'] as $subjectid_arr) {
					//删除对应投票的选项
					$this->db2 = pc_base::load_model('vote_option_model');
					$this->db2->del_options($subjectid_arr);
					$this->db->update(array('status'=>0), array('id'=>$subjectid_arr));
				}
				//记录行为日志
				$log_content = '<span style="color:red;">删除投票</span>[投票id：'.$subjectid.']';
				$this->manage_admin_log($log_content);
				showmessage(L('operation_success'),'?m=vote&c=vote');
			}else{
				$subjectid = intval($_GET['subjectid']);
	            $subject = $_GET['subject'];
				if($subjectid < 1) return false;
				//删除对应投票的选项
				$this->db2 = pc_base::load_model('vote_option_model');
				$this->db2->del_options($subjectid);

				//删除投票
				//$this->db->delete(array('subjectid'=>$subjectid));
				$result = $this->db->update(array('status'=>0), array('id'=>$subjectid));
				if($result)
				{
				    //记录行为日志
				    $log_content = '<span style="color:red;">删除投票</span>[投票id：'.$subjectid.'；标题：'.$subject.']';
				    $this->manage_admin_log($log_content);
					showmessage(L('operation_success'),'?m=vote&c=vote');
				}else {
					showmessage(L("operation_failure"),'?m=vote&c=vote');
				}
			}
				
			showmessage(L('operation_success'), HTTP_REFERER);
		}
	}
	/**
	 * 说明:删除对应投票选项
	 * @param  $optionid
	 */
	public function del_option() {
		$result = $this->db2->del_option($_GET['optionid']);
		if($result) {
			echo 1;
		} else {
			echo 0;
		}
	} 
	
	
	/**
	 * 投票模块配置
	 */
	public function setting() {
		//读取配置文件
		$data = array();
 		$siteid = $this->get_siteid();//当前站点 
		//更新模型数据库,重设setting 数据. 
		$m_db = pc_base::load_model('module_model');
		$data = $m_db->select(array('module'=>'vote'));
		$setting = string2array($data[0]['setting']);
		$now_seting = $setting[$siteid]; 
 		if(isset($_POST['dosubmit'])) {
			//多站点存储配置文件
			$siteid = $this->get_siteid();//当前站点
			$setting[$siteid] = $_POST['setting'];
  			setcache('vote', $setting, 'commons');  
			//更新模型数据库,重设setting 数据. 
 			$set = array2string($setting);
			$m_db->update(array('setting'=>$set), array('module'=>ROUTE_M));
			showmessage(L('setting_updates_successful'), '?m=vote&c=vote&a=init');
		} else {
			@extract($now_seting);
			pc_base::load_sys_class('form', '', 0);
			//模版
			pc_base::load_app_func('global', 'admin');
			$siteid = $this->get_siteid();
			$template_list = template_list($siteid, 0);
			$site = pc_base::load_app_class('sites','admin');
			$info = $site->get_by_id($siteid);
			foreach ($template_list as $k=>$v) {
				$template_list[$v['dirname']] = $v['name'] ? $v['name'] : $v['dirname'];
				unset($template_list[$k]);
			}
			include $this->admin_tpl('setting');
		}
	}


	/**
	 * 检查表单数据
	 * @param	Array	$data	表单传递过来的数组
	 * @return Array	检查后的数组
	 */
	private function check($data = array()) {
		if($data['name'] == '') showmessage(L('name_plates_not_empty'));
		if(!isset($data['width']) || $data['width']==0) {
			showmessage(L('plate_width_not_empty'), HTTP_REFERER);
		} else {
			$data['width'] = intval($data['width']);
		}
		if(!isset($data['height']) || $data['height']==0) {
			showmessage(L('plate_height_not_empty'), HTTP_REFERER);
		} else {
			$data['height'] = intval($data['height']);
		}
		return $data;
	}
		
	/**
	 * 投票结果统计
	 */
	public function statistics() {
			$subjectid = intval($_GET['subjectid']);
			if(!$subjectid){
				showmessage(L('illegal_operation'));
			}
			$show_validator = $show_scroll = $show_header = true;
 			//获取投票信息
			$sdb = pc_base::load_model('vote_data_model'); //加载投票统计的数据模型
			$sql = "select count(distinct userid) as count from nsrweb_vote_data where subjectid = $subjectid";
			$sdb->query($sql);
			$num = $sdb->fetch_array();
			$sql_count = "select data,count(*) as count from nsrweb_vote_data where subjectid = $subjectid group by data";
			$sdb->query($sql_count);
			$res = $sdb->fetch_array();
			$vote_data =array();
			foreach ($res as $v) {
				$vote_data[$v['data']] = $v['count'];
			}
   //      	$infos = $sdb->select("subjectid = $subjectid",'data');	
   //        	//新建一数组用来存新组合数据
   //      	$total = 0;
   //      	$vote_data =array();
			// $vote_data['total'] = 0 ;//所有投票选项总数
			// $vote_data['votes'] = 0 ;//投票人数
			// //循环每个会员的投票记录
			// foreach($infos as $subjectid_arr) {
			// 		extract($subjectid_arr);
 		// 			$arr = string2array($data);
 		// 			foreach($arr as $key => $values){
 		// 				$vote_data[$key]+=1;
			// 		}
  	// 				$total += array_sum($arr);
			// 		$vote_data['votes']++ ;
			// }
			$vote_data['total'] = 0; //投票总人数
			$vote_data['usertotal'] = 0; //投票总数
 			$vote_data['total'] = $num[0]['count'];
 			$vote_data['usertotal'] = $sdb->count("subjectid = $subjectid");
 			//取投票选项
			$options = $this->db2->get_options($subjectid);	
			include $this->admin_tpl('vote_statistics');	
	}
	
	/**
	 * 投票会员统计
	 */
	public function statistics_userlist() {
			$subjectid = $_GET['subjectid'];
			if(empty($subjectid)) return false;
 			$show_validator = $show_scroll = $show_header = true;
			$where = array ("subjectid" => $subjectid);
			$sdb = pc_base::load_model('vote_data_model'); //调用统计的数据模型
 			$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
			$infos = $sdb->listinfo($where,'time DESC',$page,'7');
			$pages = $sdb->pages;
			include $this->admin_tpl('vote_statistics_userlist');
	}
	
	/**
	 * 说明:生成JS投票代码
	 * @param $subjectid 投票ID
	 */
	function update_votejs($subjectid){
 			if(!isset($subjectid)||intval($subjectid) < 1) return false;
			//解出投票内容
			$info = $this->db->get_subject($subjectid);
			if(!$info) showmessage(L('not_vote'));
			extract($info);
 			//解出投票选项
			$options = $this->db2->get_options($subjectid);
 			ob_start();
 			include template('vote', $template);
			$voteform = ob_get_contents();
			ob_clean() ;
	        @file_put_contents(CACHE_PATH.'vote_js/vote_'.$subjectid.'.js', $this->format_js($voteform));
	        
	}
	
	/**
	 * 更新js
	 */
	public function create_js() {
 		$infos = $this->db->select(array('siteid'=>$this->get_siteid()), '*');
		if(is_array($infos)){
			foreach($infos as $subjectid_arr) {
				$this->update_votejs($subjectid_arr['subjectid']);
			}
		}
		showmessage(L('operation_success'),'?m=vote&c=vote');
	}
	
	/**
	 * 说明:对字符串进行处理
	 * @param $string 待处理的字符串
	 * @param $isjs 是否生成JS代码
	 */
	function format_js($string, $isjs = 1){
		$string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
		return $isjs ? 'document.write("'.$string.'");' : $string;
	}
	
	/**
	 * 投票调用代码
	 * 
	 */ 
 	public function public_call() {
 		$_GET['subjectid'] = intval($_GET['subjectid']);
		if(!$_GET['subjectid']) showmessage(L('illegal_action'), HTTP_REFERER, '', 'call');
		$r = $this->db->get_one(array('id'=>$_GET['subjectid']));
		include $this->admin_tpl('vote_call');
	}
	/**
	 * 信息选择投票接口
	 */
	public function public_get_votelist() {
		$infos = $this->db->listinfo(array('siteid'=>$this->get_siteid()),'id DESC',$page,'10');
		$target = isset($_GET['target']) ? $_GET['target'] : '';
		include $this->admin_tpl('get_votelist');
	}
	
	/**
	 * 单个投票选项订单情况
	 * 2017-12-09 16:17:07
	 * author：angel_in_us
	 */
	public function order_support() {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $page = $_GET['page']?(int)$_GET['page']:1;
        $num = $_GET['num']?(int)$_GET['num']:10;
        $id = $_REQUEST['id'];
        $info = $this->db2->get_one(array('id'=>$id));
        $sql="select p.*,c.* from nsrweb_order as p LEFT JOIN nsrweb_order_detail as c on p.id = c.order_id where p.siteid=1 and p.order_type=1 and  source_id=".$id;
        if (isset($_GET['user_name']) && $_GET['user_name']) {
        	$username = trim($_GET['user_name']);
        	$sql .= " and p.user_name like '%$username%' ";
        }
        if (isset($_GET['order_num']) && $_GET['order_num']) {
        	$order_num = trim($_GET['order_num']);
        	$sql .= " and p.order_num = " . $order_num;
        }
		$lists = $this->db->my_listinfos($sql, $page, $num);;
		//var_dump($info);die;
		$target = isset($_GET['target']) ? $_GET['target'] : '';
		include $this->admin_tpl('order_support');
	}
	
}
?>